<template>
  <div class="flow-actions">
    <el-button type="danger" :disabled="store.onClickType === null" @click="remove" text>
      <Icon icon="ep:delete" class="mr-5px" />删除
    </el-button>
    <el-button type="danger" @click="clear" text>
      <Icon icon="ep:delete" class="mr-5px" />清空
    </el-button>
    <el-button type="primary" @click="exportFlow">
      <Icon icon="ep:document" class="mr-5px" />生成话术
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ProcessApi, ProcessVO } from '@/api/system/process'
import { useFlowStore } from '@/store/modules/flow'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as _ from 'lodash-es'

const store = useFlowStore()

const props = defineProps<{ info: ProcessVO }>()
function remove() {
  // 获取当前操作类型
  const currentType = store.onClickType

  // 类型映射
  const typeMap = {
    node: { confirm: '确定要删除该节点吗？', success: '节点删除成功', removeFun: store.removeNode },
    edge: { confirm: '确定要删除该连线吗？', success: '连线删除成功', removeFun: store.removeEdge }
  }

  // 确认操作
  ElMessageBox.confirm(typeMap[currentType].confirm, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 执行删除操作
      typeMap[currentType].removeFun()
      // 动态成功提示
      ElMessage.success(typeMap[currentType].success)
    })
    .catch(() => {})
}

function clear() {
  ElMessageBox.confirm('确定要清空所有节点吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 循环删除所有节点
      store.nodes.forEach((node) => {
        if (node.data.type === 'inout') return
        store.removeNodes(node.id, true)
      })
    })
    .catch(() => {
      // onCancel
    })
}

function exportFlow() {
  const flowObj = store.flowToObj()
  const { edges, nodes } = flowObj
  if (edges.length >= nodes.length - 1 && !nodes.every((node) => node.data.type === 'inout')) {
    ElMessageBox.confirm(' 确定要生成话术吗？', ' 提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        const json = JSON.stringify(flowObj)
        const { record, ...others } = props.info
        const result = await ProcessApi.updateProcess({ record: json, ...others })
        if (result) {
          ElMessage.success('生成话术成功')
        }
      })
      .catch(() => {
        // onCancel
      })
    return
  }
  ElMessage.error('还有节点没有连完线或者只有开始和结束节点')
}
</script>

<style lang="less" scoped>
.flow-actions {
  display: flex;
  gap: 6px;
  align-items: center;
}
</style>
